package ink.sunflower.security.security;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zhaokuii11@163.com
 * @create 2022-06-05 22:33
 * @Description token操作工具类
 */
@Component
public class TokenManager {

    // token有效时长
    private Long tokenEcpiration = 24 * 60 * 60 * 1000L;
    //编码密钥
    private String tokenSignKey = "123456";

    //1. 根据用户生成token
    public String createToken(String username) {
        String token = Jwts.builder()
                .setSubject(username) //设置主体部分
                .setExpiration(new Date(System.currentTimeMillis() + tokenEcpiration)) //设置有效时长
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //2. 根据token字符串得到用户信息
    public String getUserInfo(String token) {
        String userInfo = Jwts.parser() //解析
                .setSigningKey(tokenSignKey) //设置密钥
                .parseClaimsJws(token) //解析
                .getBody().getSubject();//获取用户信息
        return userInfo;
    }

    //3. 删除token
    public void removeToken(String token) {

    }
}
